package com.nervenets.general.utils;

import com.alibaba.fastjson.JSON;
import com.nervenets.general.exception.LogicException;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Objects;

import static org.apache.commons.lang3.StringUtils.trim;

@Slf4j
public class AESUtils {
    /**
     * 加密固定key与iv的字符串
     *
     * @param data 加密内容
     * @param key  key
     * @param iv   iv
     * @return 加密成功后的字符串
     */
    public static String encryptData(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new String(Base64.encodeBase64(encrypted));
        } catch (Exception e) {
            log.info("aes 加密 失败 ：" + e.getMessage());
        }
        return null;
    }

    /**
     * 解密固定key与iv的字符串
     *
     * @param data 加密成功后的字符串
     * @param key  key
     * @param iv   iv
     * @return 原加密内容
     */
    public static String decryptString(String data, String key, String iv) {
        try {
            byte[] encrypted1 = Base64.decodeBase64(data.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 随机加密过期对象
     *
     * @param data        加密内容
     * @param expiredTime 过期时间
     * @return 加密成功后的字符串
     */
    public static String encryptData(String data, long expiredTime) {
        String ivSourceKey = StringUtils.randomString(16);
        String mergeKey = StringUtils.randomString(1);
        String ivKey = ivSourceKey.replaceAll("[0-9]", mergeKey);
        return mergeKey + ivSourceKey + "/" + AESUtils.encryptData(JSON.toJSONString(new Data(data, expiredTime)), ivKey, ivKey);
    }

    /**
     * 随机加密字符
     *
     * @param data 加密内容
     * @return 加密成功后的字符串
     */
    public static String encryptString(String data) {
        String ivSourceKey = StringUtils.randomString(16);
        String mergeKey = StringUtils.randomString(1);
        String ivKey = ivSourceKey.replaceAll("[0-9]", mergeKey);
        //System.out.println(String.format("decryptString ivKey:%s ivSourceKey:%s mergeKey:%s", ivKey, ivSourceKey, mergeKey));
        return mergeKey + ivSourceKey + "/" + encryptData(data, ivSourceKey, ivKey);
    }

    /**
     * 随机解密含过期的字符串
     *
     * @param data 加密成功后的字符串
     * @return 解密结果
     */
    public static String decryptData(String data) {
        return Objects.requireNonNull(decryptDataObject(data)).getTxt();
    }

    /**
     * 随机解密含过期时间的字符串
     *
     * @param data             加密成功后的字符串
     * @param expiredException 如果过期抛的异常
     * @return 解密结果
     */
    public static String decryptData(String data, Exception expiredException) throws Exception {
        Data obj = Objects.requireNonNull(decryptDataObject(data));
        if (obj.getT() > 0 && obj.getT() < JodaUtils.getTimestamp()) throw expiredException;
        return obj.getTxt();
    }

    /**
     * 随机解密含过期时间的字符串
     *
     * @param data 加密成功后的字符串
     * @return @Data
     */
    public static Data decryptDataObject(String data) {
        try {
            if (StringUtils.isBlank(data)) return null;
            return JSON.parseObject(decryptString(data), Data.class);
        } catch (Exception e) {
            throw new LogicException("解密失败");
        }
    }

    /**
     * 随机解密字符串
     *
     * @param data 加密内容
     * @return 解密结果
     */
    public static String decryptString(String data) {
        try {
            if (StringUtils.isBlank(data)) return null;
            int firstSlashIndex = data.indexOf("/");
            String ivSourceKey = data.substring(0, firstSlashIndex);
            final String base64Data = data.substring(firstSlashIndex + 1);

            final String mergeKey = ivSourceKey.substring(0, 1);
            ivSourceKey = ivSourceKey.substring(1);

            String ivKey = ivSourceKey.replaceAll("[0-9]", mergeKey);
            //System.out.println(String.format("decryptString ivKey:%s ivSourceKey:%s mergeKey:%s", ivKey, ivSourceKey, mergeKey));
            return trim(decryptString(base64Data, ivSourceKey, ivKey));
        } catch (Exception e) {
            throw new LogicException("解密失败");
        }
    }

    @Setter
    @Getter
    @AllArgsConstructor
    @NoArgsConstructor
    @SuperBuilder
    static class Data {
        @ApiModelProperty("内容")
        private String txt;
        @ApiModelProperty("过期时间")
        private long t;
    }
}
